package com.hzh.reverse.server.handler;

import org.w3c.dom.events.Event;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;


public class ClientConnectionHandler extends ChannelInboundHandlerAdapter {

    EventLoopGroup publicRequestBoss = new NioEventLoopGroup(1);
    EventLoopGroup publicRequestWorker = new NioEventLoopGroup();

    ServerBootstrap publicServer = new ServerBootstrap();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        if (publicRequestBoss == null)
            publicRequestBoss = new NioEventLoopGroup(1);
        if (publicRequestWorker == null)
            publicRequestWorker = new NioEventLoopGroup(1);
        if (publicServer == null) {
            publicServer = new ServerBootstrap();
        }

        Channel clientToPublicChannel = ctx.channel();
        System.out.println("======客户端连接=======" + clientToPublicChannel.remoteAddress());
        // EventLoopGroup publicRequestBoss=new NioEventLoopGroup(1);
        // EventLoopGroup publicRequestWorker = new NioEventLoopGroup();

        // ServerBootstrap publicServer = new ServerBootstrap();

        publicServer.group(clientToPublicChannel.eventLoop(), publicRequestWorker).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new PublicConnectionHandler(clientToPublicChannel)).bind(9979).sync().channel()
                .closeFuture().sync();

        clientToPublicChannel.read();

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                System.out.println("响应给服务端"+ctx.channel().remoteAddress().toString());

        Channel serverChannel = PublicConnectionHandler.channelMap.get(ctx.channel().remoteAddress().toString());
        serverChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture arg0) throws Exception {

                System.out.println("完成响应给服务端");
                // PublicConnectionHandler.channelQueue.add(arg0.channel());
            }
        });

    }
}
